<?php
/**
 * Created by PhpStorm.
 * User: xaq
 * Date: 2017/7/10
 * Time: 15:36
 */

namespace app\index\controller;

use app\lib\exception\CodeException;
use think\Request;
use app\lib\exception\TokenException;

class Oauth extends BaseController
{
    protected $auth_cookie_current_openid;
    //登陆跳转
    public function actionLogin($scope='snsapi_base'){
        //1、获取code
        $app_id = config('wx.app_id');
        $redirect_uri = config('setting.baseUrl').'/index/oauth/callback';
        //$scope = "snsapi_base";
        //$scope = input('get.scope');
        $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=%s&state=123#wechat_redirect ";
        $request_url = sprintf($url,$app_id,$redirect_uri,$scope);
        return $this->redirect($request_url);
    }

    //登陆跳转后返回页面
    public function actionCallback(){
        $code = input('get.code');
        if(!$code){
            throw new CodeException();
        }

        //2、通过code获取网页授权的access_token
        $app_id = config('wx.app_id');
        $app_secret = config('wx.app_secret');
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code ";
        $request_url = sprintf($url,$app_id,$app_secret,$code);

        $result = curl_get($request_url);
        $resultObj = json_decode($result,true);
        $access_token = isset($resultObj['access_token'])?$resultObj['access_token']:'';
        if(!$access_token) {
            throw new TokenException([
               'msg' => 'access_token已过期或者无效'
            ]);
        }

        //4、拉取用户信息(需scope为 snsapi_userinfo)
        $openid = isset($resultObj['openid'])?$resultObj['openid']:'';
        $scope = isset($resultObj['scope'])?$resultObj['scope']:'';

        //将openid存储到cookie中
        cookie($this->auth_cookie_current_openid,$openid);

        if($scope == 'snsapi_userinfo'){
            $userUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s&lang=zh_CN";
            $userRequestUrl = sprintf($userUrl,$access_token,$openid);
            $userInfo = curl_get($userRequestUrl);
            //return json($userInfo);
        }
        return $this->redirect(config('setting.baseUrl').'/index/call');

    }
}